package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.model.Checkin;
import com.example.dao.CheckinMapper;
import com.example.model.User;
import com.example.service.ICheckinService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Hello
 * @since 2024-07-12
 */
@Service
public class CheckinServiceImpl extends ServiceImpl<CheckinMapper, Checkin> implements ICheckinService {
    @Autowired
    CheckinMapper checkinMapper;
    @Override
    public Boolean checkIn(Integer userID) {
        UpdateWrapper<Checkin> updateWrapper = new UpdateWrapper<>();
        Checkin checkInInfo = getCheckInInfo(userID);
        LocalDate lastSign = checkInInfo.getLastSign();
        LocalDate yesterday = LocalDate.now().minusDays(1);
        Integer continuityDays = checkInInfo.getContinuityDays();
        Integer seriesDays = checkInInfo.getSeriesDays();
        if (lastSign.isEqual(yesterday)) {
            continuityDays++;
        } else {
            continuityDays = 0;
        }
        seriesDays++;
        updateWrapper.eq("user_id",userID).set("last_sign", LocalDate.now()).set("series_days",seriesDays).set("continuity_days",continuityDays);
        if(checkinMapper.update(updateWrapper) != 1) return false;
        return true;
    }

    @Override
    public Checkin getCheckInInfo(Integer userID) {
        QueryWrapper<Checkin> checkInQueryWrapper = new QueryWrapper<>();
        checkInQueryWrapper.eq("user_id",userID);
        Checkin checkin = checkinMapper.selectOne(checkInQueryWrapper);
        return checkin;
    }
}
